<template>
	<view @imgList="imgList" style="margin-left: 20rpx;">
			<u-upload  :fileList="fileList" @afterRead="afterRead" @delete="deletePic"
				:sizeType="sizeType" @clickPreview="clickPreview"  multiple :disabled="disabled"
				:formkey="formkey">
				<view class="material-add">
					<u-button class='upload-btn' :disabled="disabled" text="上传图片"></u-button>
				</view>
			</u-upload>
	</view>
</template>
<script>
	import {
		compressImg
	} from '@/utils/util.js'
	export default {
		data() {
			return {
				currentValue: false,
				fileList: [],
				sizeType: ['compressed'],
				fileMaxSize: 2 * 1024 * 1024, // 默认最大为2M
				fileMinSize: 50 * 1024 // 最小为50KB
			}
		},
		methods: {
			clickPreview(url, lists, name) {
				console.log('预览图片', url, lists, name)
			},
			getCompressionRatio(fileSize) {
				const multiple = (fileSize / this.fileMaxSize).toFixed(2) // 获取文件大小倍数，生成质量比
				let compressionRatio = 1
				if(multiple > 5) {
					compressionRatio = 0.5
				} else if (multiple > 4) {
					compressionRatio = 0.6
				} else if (multiple > 3) {
					compressionRatio = 0.7
				}else if (multiple > 2) {
					compressionRatio = 0.8
				} else if (multiple > 1) {
					compressionRatio = 0.9
				} else {
					compressionRatio = 2
				}
				return compressionRatio;
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList`].length

				for (let index in lists) {
					const item = lists[index]
					const fileSize = item.size
					const fileName = item.name ?? ''
					if (fileSize > this.fileMaxSize) {
						const compressionRatio = this.getCompressionRatio(fileSize)
						if (compressionRatio > 1) {
							uni.$u.toast('文件' + fileName + '大于10M')
							return false
						}
						// 自动压缩图片'
						await this.compressImg(item, compressionRatio)
						if (item.size > this.fileMaxSize) {
							uni.$u.toast('文件' + fileName + '压缩后超出2M')
							return false
						}
					}

					if (item.size < this.fileMinSize) {
						uni.$u.toast('文件' + fileName + '不能小于50KB')
						return false
					}

					this[`fileList`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				}
				for (let i = 0; i < lists.length; i++) {

					const result = await this.uploadFilePromise(lists[i].url)
					// 垃圾回收
					window.URL.revokeObjectURL(lists[i].url)
					console.log('上传结果', result)
					let item = this[`fileList`][fileListLen]
					this[`fileList`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '上传成功',
						url: result
					}))
					fileListLen++
				}
			},
			compressImg(source, compressionRatio) {
				return new Promise((resolve, reject) => {
					compressImg(source.url, compressionRatio, source.type, compressRes => {
						resolve(compressRes);
					})
				}).then((res) => {
					source.size = res.size
					// window.URL.revokeObjectURL(source.url) // 删除被压缩的缓存文件,这里注意，如果是相册选择上传，可能会删除相册的图片
					console.log('压缩成功')
					source.url = res.source
					source.thumb = res.source
					return source
				}).catch(err => {
					console.log('图片压缩失败', err)
				})
			},
			uploadFilePromise(url) {
				let that = this
				return new Promise((resolve, reject) => {
					const uploadTask = uni.uploadFile({
						url: `${getApp().globalData.baseUrl}/api/common/upload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							"blade-auth": "Bearer xxxxxxxxxxxxx",
							"tenantCode": tenantCode
						},
						success: (uploadFileRes) => {
							if (uploadFileRes.statusCode === that.Response.OK) {
								const data = JSON.parse(uploadFileRes.data)
								if (data.code === that.Response.OK) {
									console.log('form components upload uploadFilePromise onchange',
										uploadFileRes)
									let fileId = data.data[0].id;
									const sourceUrl = 'https://xxxxxxx/download-document/id/' + fileId;
									that.data.value.push({
										id: fileId,
										name: data.data[0].name,
										source: sourceUrl
									});
									// 添加图片数量
									that.data.count = that.fileList.length
									that.$emit('change', that.data, that.formkey)
									setTimeout(() => {
										resolve(sourceUrl)
									}, 500)
								} else {
									uni.showToast({
										title: data.msg,
										icon: 'none',
										duration: that.ShowToast.DURATION
									});
								}
							} else {
								console.log(uploadFileRes)
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: that.ShowToast.DURATION
								});
							}
						},
						fail(error) {
							// reject(false)
							uni.$u.toast(error.errMsg)
							console.log('图片上传失败', error)
						}
					});

					// uploadTask.onProgressUpdate((res) => {
					// 	console.log('上传进度' + res.progress);
					// 	console.log('已经上传的数据长度' + res.totalBytesSent);
					// 	console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

					// 	// 测试条件，取消上传任务。
					// 	if (res.progress > 50) {
					// 		uploadTask.abort();
					// 	}
					// });
				})
			},
		}
	} 
<script/>
